#include "mainform.h"
#include "ui_mainform.h"
#include "qqtcore.h"
#include "qqtsqlquery.h"
#include "qqtframe.h"
#include "framecore.h"

#include "caidan1button.h"
#include "caidan1groupbutton.h"

#include <QMouseEvent>

#include <qqtclickdialog.h>
#include <qqtmaskwidget.h>
#include <centraldisplaydialog.h>

MainForm::MainForm ( QWidget* parent ) :
    HuanFrame ( parent ),
    ui ( new Ui::MainForm )
{
    ui->setupUi ( this );

    //先构造成员，后构造主类。
    //ptime();

    this->setImageStyle ( QQTCENTER );
    this->setPixmap ( skin ( "demo/bk_main.png" ) );

    protocol = DEMOSerialPort ( this );

    initLightsDBtoDict();

    initCaidan1();
    initCaidan2();
    initCaidan3();
    initCaidan4();

    centralForm = new CentralControlForm ( this );
    moveCenter ( centralForm, this );
    pline() << centralForm->geometry();
    pline() << this->geometry();
    pline() << this->rect();
    centralForm->show();

    connect ( centralForm, SIGNAL ( currentIndexChanged ( int ) ),
              this, SLOT ( setCurrentIndex ( int ) ) );

    ui->stackedWidget->setCurrentIndex ( 0 );

    initCaidan4b();
    initCaidan3c();
    initCaidan3d();
    initCaidan4a();
    initCaidan4c();
    initCaidan4e();
    initCaidan3a();
    initCaidan3b();

    //only once
    //initDengDB();

    //ui->caidan1->initButtons3();

    CentralDisplayDialog* dlg = new CentralDisplayDialog ( this );
    //dlg->show();
    dlg->hide();
    moveCenter ( dlg, this );
    QList<int> ln; ln << 1 << 2 << 3;
    dlg->setLightNo ( ln );
}

MainForm::~MainForm()
{
    delete ui;
}

void MainForm::initMainForm()
{
}

void MainForm::mouseReleaseEvent ( QMouseEvent* event )
{
    static int i = 0;
    i = i % 4;
    //pline() << i;
    //ui->stackedWidget->setCurrentIndex ( i );
    i++;
}

void MainForm::initCaidan1()
{
    initCaidan01Huan();

    initCaidan01A();
}

void MainForm::initCaidan2()
{
    ui->caidan2->setTitle ( "EDIT SCENES" );
    ui->caidan2->setBackButton ( "SELECT", "" );

    //sub form
    //02里小按钮一按,嗖嗖的去了02B
    //02小按钮双击,去了02e
    initCaidan02Scene();

    //main form
    connect ( ui->caidan2, SIGNAL ( sigBackClick() ),
              this, SLOT ( changeMainForm() ) );

    initCaidan02B();
    initCaidan02C();
    initCaidan02D();
    initCaidan02E();
    initCaidan021();

    ui->widget_11->setText ( "ADD" );
    ui->widget_24->setText ( "DELETE" );
    ui->widget_11->setIcon ( skin ( "demo/icon_default.png" ) );
    ui->widget_24->setIcon ( skin ( "demo/icon_default.png" ) );
}

void MainForm::initCaidan3()
{
    QWidget* w[4] = {0};

    w[0] = ui->w301;
    w[1] = ui->w302;
    w[2] = ui->w303;
    w[3] = ui->w304;

    for ( int i = 0 ; i < 4 ; i++ )
    {
        w[i]->setGeometry ( calculatePosition ( this, i, this->width() / 2 - 40 - 10, 40, 8, -70  ) );
    }

    ui->w301->setText ( "GROUP\nSCENES" );
    ui->w302->setText ( "BRIGHTS" );
    ui->w303->setText ( "SPEEDS" );
    ui->w304->setText ( "MUSIC" );
}

void MainForm::initCaidan4()
{
    QWidget* w[5] = {0};

    w[0] = ui->w401;
    w[1] = ui->w402;
    w[2] = ui->w403;
    w[3] = ui->w404;
    w[4] = ui->w405;

    for ( int i = 0 ; i < 5 ; i++ )
    {
        w[i]->setGeometry ( calculatePosition ( this, i, this->width() / 2 - 40 - 10, 40, 10, -72  ) );
    }

    ui->w401->setText ( "SEARCH\nLIGHTS" );
    ui->w402->setText ( "BATTERY" );
    ui->w403->setText ( "TIME" );
    ui->w404->setText ( "STANDBY" );
    ui->w405->setText ( "INFO" );
}

void MainForm::initCaidan3a()
{
    ui->caidan3a->setTitle ( "GROUP SCENES" );
    ui->caidan3a->setBackButton ( "CONTROL", "" );

    //sub form
    connect ( ui->w301, SIGNAL ( click() ),
              this, SLOT ( changeCurrentForm() ) );

    //main form
    connect ( ui->caidan3a, SIGNAL ( sigBackClick() ),
              this, SLOT ( changeMainForm() ) );

    //init page
    init3ATabBar();
    init3ALights();
}

void MainForm::initCaidan3b()
{
    ui->caidan3b->setTitle ( "BRIGHTS" );
    ui->caidan3b->setBackButton ( "CONTROL", "" );

    //sub form
    connect ( ui->w302, SIGNAL ( click() ),
              this, SLOT ( changeCurrentForm() ) );

    //main form
    connect ( ui->caidan3b, SIGNAL ( sigBackClick() ),
              this, SLOT ( changeMainForm() ) );

    ui->label_5->installEventFilter ( this );
}

void MainForm::initCaidan3c()
{
    ui->caidan3c->setTitle ( "SPEEDS" );
    ui->caidan3c->setBackButton ( "CONTROL", "" );

    //sub form
    connect ( ui->w303, SIGNAL ( click() ),
              this, SLOT ( changeCurrentForm() ) );

    //main form
    connect ( ui->caidan3c, SIGNAL ( sigBackClick() ),
              this, SLOT ( changeMainForm() ) );

    //init content widget
    ui->lightSpeedSlider->setRange ( -5, 5 );
    QSettings set;
    int speed = set.value ( "lightSpeed", 0 ).toInt();
    ui->lightSpeedSlider->setValue ( speed );
}

void MainForm::initCaidan3d()
{
    ui->caidan3d->setTitle ( "MUSIC" );
    ui->caidan3d->setBackButton ( "CONTROL", "" );

    //sub form
    connect ( ui->w304, SIGNAL ( click() ),
              this, SLOT ( changeCurrentForm() ) );
    //main form
    connect ( ui->caidan3d, SIGNAL ( sigBackClick() ),
              this, SLOT ( changeMainForm() ) );

    //init content widgets
    //播放一个wav文件，（原打开音频输入设备），根据音频格式，提取振幅，绘制到图上。
    wavManager.setInputSourceFile ( res ( "9863.wav" ) );
    connect ( &wavManager, SIGNAL ( readyRead() ), this, SLOT ( slotPlayOut() ) );

    audioManager.outputDeviceInfo() = QQtAudioManager::defaultOutputDevice();
    audioManager.outputAudioFormat() = wavManager.inputAudioFormat();
}

void MainForm::initCaidan4b()
{
    ui->caidan4b->setTitle ( "BATTERY" );
    ui->caidan4b->setBackButton ( "SETUP", skin ( "demo/icon_default.png" ) );

    //sub form
    connect ( ui->w402, SIGNAL ( click() ),
              this, SLOT ( changeCurrentForm() ) );
    //main form
    connect ( ui->caidan4b, SIGNAL ( sigBackClick() ),
              this, SLOT ( changeMainForm() ) );
}

void MainForm::initCaidan4a()
{
    ui->caidan4a->setTitle ( "SEARCH LIGHTS" );
    ui->caidan4a->setBackButton ( "SETUP", "" );

    //sub form
    connect ( ui->w401, SIGNAL ( click() ),
              this, SLOT ( changeCurrentForm() ) );
    //main form
    connect ( ui->caidan4a, SIGNAL ( sigBackClick() ),
              this, SLOT ( changeMainForm() ) );

    //init searching lights
    init4ASearchingLights();
}

void MainForm::initCaidan4c()
{
    ui->caidan4c->setTitle ( "SEARCH LIGHTS" );
    ui->caidan4c->setBackButton ( "SETUP", "" );

    //sub form
    connect ( ui->w403, SIGNAL ( click() ),
              this, SLOT ( changeCurrentForm() ) );
    //main form
    connect ( ui->caidan4c, SIGNAL ( sigBackClick() ),
              this, SLOT ( changeMainForm() ) );

    ui->label_6->installEventFilter ( this );
    ui->label_7->installEventFilter ( this );
    ui->label_8->installEventFilter ( this );
    ui->label_9->installEventFilter ( this );
}

void MainForm::initCaidan4e()
{
    ui->caidan4e->setTitle ( "INFO" );
    ui->caidan4e->setBackButton ( "SETUP", "" );

    //sub form
    connect ( ui->w405, SIGNAL ( click() ),
              this, SLOT ( changeCurrentForm() ) );
    //main form
    connect ( ui->caidan4e, SIGNAL ( sigBackClick() ),
              this, SLOT ( changeMainForm() ) );
}

void MainForm::initDengDB()
{
    QQtSqlDatabaseConnection db;
    db = newDatabaseConnection();
    QString dbName = QDir (
                         DB_PATH ).relativeFilePath ( "/Users/abel/Develop/a0-develop/LightUnderWater/App/AppRoot/db/Lights.db" );
    //pline() << dbName;
    useDatabase ( db,  dbName );

    QQtSqlQuery query ( db );
    //query.setDebug ( true );

#if 1
    query.exec ( "delete from lightGroup where 1=1" );
    query.exec ( "delete from light where 1=1" );
    query.exec ( "delete from lightScene where 1=1" );
    query.exec ( "delete from lightGroupUsing where 1=1" ); //显示在a1的灯群组
    query.exec ( "delete from lightSearching where 1=1" ); //搜索到的灯编号和类型
#endif

#if 1
    QStringList sceneName;
    sceneName << "name" << "timesMinite" << "lightTime" << "icon";

    for ( int i = 1; i <= 48; i++ )
    {
        QStringList sceneValue;

        sceneValue << QString ( "场景%1" ).arg ( i, 2, 10, QChar ( '0' ) )
                   << QString::number ( 1 )
                   << QString::number ( 10 )
                   << skin ( "demo/icon_default.png" );

        query.insert ( "lightScene", sceneName, sceneValue );
    }

#endif

#if 1
    QStringList lightsName;
    lightsName << "deley" << "loop" << "scene";

    for ( int i = 1; i <= 999; i++ )
    {
        QStringList lightsValue;

        lightsValue << QString::number ( 0 )
                    << QString::number ( 1 )
                    << "场景01";

        query.insert ( "light", lightsName, lightsValue );
    }

#endif

#if 1
    QStringList groupName;
    groupName << "name" << "lights";

    for ( int i = 1; i <= 20; i++ )
    {
        QStringList groupValue;

        groupValue << QString ( "群组%1" ).arg ( i, 2, 10, QChar ( '0' ) )
                   << "1";

        query.insert ( "lightGroup", groupName, groupValue );
    }

#endif

    query.finish();

    closeDatabase ( db );
    //deleteDatabaseConnection ( db );
}

void MainForm::translateIconTable ( QWidget* parent, const QList<QWidget*>& iconList, int x, int colNum , int spacing )
{
    QListIterator<QWidget*> itor ( iconList );
    int index = 0;
    while ( itor.hasNext() )
    {
        QWidget* w = itor.next();
        int i = index % colNum;
        w->setGeometry ( i * x, ( index - 1 ) / colNum * x, x, x );
        w->show();
        index++;
    }
}

void MainForm::init4ASearchingLights()
{
    //把scrollArea拉长到相应的大小。宽度保持不变。
    //ui->lightsTable->setFixedWidth ( 480 );

    if ( m4ALightsList.size() <  gSearchingLightsDict.size() )
    {
        int size = gSearchingLightsDict.size() - m4ALightsList.size();
        for ( int i = 0; i < size; i++ )
        {
            QLabel* w = new QLabel ( ui->lightsTableContent );
            //w->setAutoFillBackground(true);
            w->setAlignment ( Qt::AlignCenter );
            w->setStyleSheet ( "QLabel{background-color:#EC8598;}" );
            m4ALightsList.push_back ( w );
        }
    }

    QListIterator<QLabel*> itt ( m4ALightsList );
    while ( itt.hasNext() )
    {
        QLabel* l = itt.next();
        l->setHidden ( true );
    }

    //根据查询命令，或者上报的search命令，把dict里的灯绘制到这里。
    const qint8 colNum = 8;
    pline() << gSearchingLightsDict.getTypeName() << gSearchingLightsDict.size();
    QQtDictionaryListIterator itor ( gSearchingLightsDict.getList() );
    int index = 0;
    //过滤第一个 0
    if ( itor.hasNext() )
    {
        itor.next();
        index++;
    }

    while ( itor.hasNext() )
    {
        const QQtDictionary& node = itor.next();
        //pline() << node;

        QLabel* w = m4ALightsList[index];
        w->setText ( QString::number ( index ) );
        int type = node["type"].getValue().toInt();
        if ( 0 != type )
            w->setStyleSheet ( "QLabel{background-color:#EC8599;}" );
        //pline() << w;

        //每行的数目是确定的。
        int i = ( index - 1 ) % colNum;

        int iconW = 50;
        w->setGeometry ( i * iconW, ( index - 1 ) / colNum * iconW, iconW - 2, iconW - 2 );
        w->show();

        ui->lightsTableContent->setFixedHeight ( ( ( index - 1 ) / colNum + 1 ) * iconW );

        index++;
    }
}

void MainForm::init3ATabBar()
{
    static bool bInited = false;

    //only once
    if ( bInited == true )
        return;
    bInited = true;

    ui->sceneBar->setShape ( QTabBar::RoundedWest );
    ui->sceneBar->setIconStyle ( QQtPictureTabBar::IconStyle_Top_And_BottomText );
    ui->sceneBar->setIconSize ( QSize ( 30, 30 ) );
    ui->sceneBar->setLayoutSpacing ( 0 );
    ui->sceneBar->setStyleSheet ( "QTabBar::tab{ width:50px; height:50px;}" );

    QFont font = qApp->font();
    font.setPixelSize ( 10 );
    ui->sceneBar->setTextFont ( font );

    QQtDictionaryListIterator itor ( gLightSceneDict.getList() );
    //pline() << gLightSceneDict;
    int index = 0;
    while ( itor.hasNext() )
    {
        const QQtDictionary& node = itor.next();
        if ( node.isEmpty() )
        {
            index++;
            continue;
        }
        //pline() << node;
        //pline() << node["name"] << node["icon"];
        QString name = node["name"].getValue().toString();
        QString icon = node["icon"].getValue().toString();
        QString iconFile = skin ( QString ( "demo/%1" ).arg ( icon )  );
        //pline() << name << icon << iconFile;
        ui->sceneBar->addTab ( QIcon ( iconFile ), name );
        ui->sceneBar->setTabIcon ( index - 1, iconFile, iconFile );
        index++;
    }


}

void MainForm::init3ALights()
{
    static bool bInited = false;

    //only once
    if ( bInited == true )
        return;
    bInited = true;

    //把scrollArea拉长到相应的大小。宽度保持不变。
    //ui->lightsTableContent->setFixedWidth ( 600 );
    //ui->saw_03a->setMouseTracking ( true );
    //ui->scrollArea_3->setMouseTracking ( true );
    ui->scrollArea_3->setVerticalScrollBarPolicy ( Qt::ScrollBarAlwaysOff );

    if ( m3ALightsList.size() <  gLightDict.size() )
    {
        int size = gLightDict.size() - m3ALightsList.size();
        for ( int i = 0; i < size; i++ )
        {
            QQtColorLabel* w = new QQtColorLabel ( ui->saw_03a );
            //w->setAutoFillBackground(true);
            w->setAlignment ( Qt::AlignCenter );
            //w->setStyleSheet ( "QLabel{background-color:#0044E7;}" );
            w->setColor ( QRgb ( 0xFEFEFE ) );
            m3ALightsList.push_back ( w );
        }
    }

    QListIterator<QQtColorLabel*> itt ( m3ALightsList );
    while ( itt.hasNext() )
    {
        QQtColorLabel* l = itt.next();
        l->setHidden ( true );
    }

    //根据查询命令，或者上报的search命令，把dict里的灯绘制到这里。
    const qint8 colNum = 7;
    pline() << gLightDict.getTypeName() << gLightDict.size();
    QQtDictionaryListIterator itor ( gLightDict.getList() );
    int index = 0;
    //过滤第一个 0
    if ( itor.hasNext() )
    {
        itor.next();
        index++;
    }

    while ( itor.hasNext() )
    {
        const QQtDictionary& node = itor.next();
        if ( node.isEmpty() )
        {
            index++;
            continue;
        }
        //pline() << node;

        QQtColorLabel* w = m3ALightsList[index];
        w->setText ( QString::number ( index ) );
        //根据灯的scene设置灯的颜色.没有scene的不设置,使用默认颜色.
        //保存在dict["color"]
        int type = node["type"].getValue().toInt();
        if ( 0 != type )
            //w->setStyleSheet ( "QLabel{background-color:#EE7799;}" );
            w->setColor ( QRgb ( 0xEE7799 ) );
        //pline() << w;

        //每行的数目是确定的。
        int i = ( index - 1 ) % colNum;

        int iconW = 50;
        w->setGeometry ( i * iconW, ( index - 1 ) / colNum * iconW, iconW - 2, iconW - 2 );
        w->show();

        ui->saw_03a->setFixedHeight ( ( ( index - 1 ) / colNum + 1 ) * iconW );

        index++;
    }
}

void MainForm::initCaidan02Scene()
{
    static bool bInited = false;

    //only once
    if ( bInited == true )
        return;
    bInited = true;

    //把scrollArea拉长到相应的大小。宽度保持不变。
    //ui->lightsTableContent->setFixedWidth ( 600 );
    //ui->saw_03a->setMouseTracking ( true );
    //ui->scrollArea_3->setMouseTracking ( true );
    ui->scrollArea_4->setVerticalScrollBarPolicy ( Qt::ScrollBarAlwaysOff );

    if ( mCaidan2BtnList.size() <  gLightSceneDict.size() )
    {
        int size = gLightSceneDict.size() - mCaidan2BtnList.size();
        for ( int i = 0; i < size; i++ )
        {
            HuanButton* w = new HuanButton ( ui->saw_02 );
            //w->setAutoFillBackground(true);
            //w->setAlignment ( Qt::AlignCenter );
            //w->setStyleSheet ( "QLabel{background-color:#0044E7;}" );
            //w->setColor ( QRgb ( 0xFEFEFE ) );
            mCaidan2BtnList.push_back ( w );
        }
    }

    QListIterator<HuanButton*> itt ( mCaidan2BtnList );
    while ( itt.hasNext() )
    {
        HuanButton* l = itt.next();
        l->setHidden ( true );
    }

    //根据查询命令，或者上报的search命令，把dict里的灯绘制到这里。
    const qint8 colNum = 5;
    pline() << gLightSceneDict.getTypeName() << gLightSceneDict.size();
    QQtDictionaryListIterator itor ( gLightSceneDict.getList() );
    int index = 0;
    //过滤第一个 0
    if ( itor.hasNext() )
    {
        itor.next();
        index++;
    }

    while ( itor.hasNext() )
    {
        const QQtDictionary& node = itor.next();
        if ( node.isEmpty() )
        {
            index++;
            continue;
        }

        //pline() << node;

        QString name = node["name"].getValue().toString();
        QString icon = node["icon"].getValue().toString();
        QString iconFile = skin ( QString ( "demo/%1" ).arg ( icon )  );
        //pline() << name << icon << iconFile;

        HuanButton* w = mCaidan2BtnList[index];
        w->setText ( name );
        w->setIcon ( iconFile );
        QFont font = qApp->font();
        font.setPixelSize ( 10 );
        w->setTextFont ( font );
        w->setIconSize ( QSize ( 56, 56 ) );
        //pline() << w;

        connect ( w, SIGNAL ( click() ), this, SLOT ( goto02BForm() ) );
        //connect ( w, SIGNAL ( doubleClick() ), this, SLOT ( goto021Form() ) );

        //每行的数目是确定的。
        int i = ( index - 1 ) % colNum;

        int iconW = 60;
        int iconH = 80;
        w->setGeometry ( i * iconW, ( index - 1 ) / colNum * iconH, iconW - 4, iconH - 4 );
        w->show();

        ui->saw_02->setFixedHeight ( ( ( index - 1 ) / colNum + 1 ) * iconH );

        index++;
    }
}

void MainForm::initCaidan02B()
{
    //ui->caidan2b->setTitle ( "INFO" );
    ui->caidan2b->setBackButton ( "SCENES", "" );

    QString iconFile = skin ( QString ( "demo/icon/icon_%1.png" ).arg ( "default" )  );
    ui->icon2b->setPixmap ( iconFile );

    //sub form
    //单击菱形 02c
    connect ( ui->sceneSlider, SIGNAL ( lingClicked ( LingWidget* ) ),
              this, SLOT ( preGoto02CForm ( LingWidget* ) ) );
    //单击矩形
    connect ( ui->sceneSlider, SIGNAL ( click() ), this, SLOT ( goto02EForm() ) );
    //长击矩形
    //...

    //单击icon 02d
    connect ( ui->icon2b, SIGNAL ( click() ), this, SLOT ( goto02DForm() ) );
    //单击icon label 021
    connect ( ui->label2b, SIGNAL ( click() ), this, SLOT ( goto021Form() ) );

    //main form
    connect ( ui->caidan2b, SIGNAL ( sigBackClick() ),
              this, SLOT ( changeMainForm() ) );
}

void MainForm::initCaidan02C()
{
    ui->caidan2c->setTitle ( "EDIT SCENES" );
    ui->caidan2c->setBackButton ( "SCENES", "" );

    //02c选择了样色以后,直接连到菱形的设置颜色的端口(函数)上.
    connect ( ui->widget_18, SIGNAL ( colorChanged ( QRgb ) ),
              this, SLOT ( lingColorChanged ( QRgb ) ) );

    //sub form
    ui->widget_18->setBackgroundPicture ( skin ( "demo/icon_yanseban.png" ) );

    //main form
    connect ( ui->caidan2c, SIGNAL ( sigBackClick() ),
              this, SLOT ( changeMainForm() ) );
}

void MainForm::initCaidan02D()
{
    static bool bInited = false;

    //only once
    if ( bInited == true )
        return;
    bInited = true;

    //把scrollArea拉长到相应的大小。宽度保持不变。
    //ui->lightsTableContent->setFixedWidth ( 600 );
    //ui->saw_03a->setMouseTracking ( true );
    //ui->scrollArea_3->setMouseTracking ( true );
    ui->scrollArea_2->setVerticalScrollBarPolicy ( Qt::ScrollBarAlwaysOff );

    if ( mCaidan2DIconList.size() <  80 )
    {
        int size = 80 - mCaidan2DIconList.size();
        for ( int i = 0; i < size; i++ )
        {
            QQtClickWidget* w = new QQtClickWidget ( ui->iconTable );
            //w->setAutoFillBackground(true);
            //w->setAlignment ( Qt::AlignCenter );
            //w->setStyleSheet ( "QLabel{background-color:#0044E7;}" );
            //w->setColor ( QRgb ( 0xFEFEFE ) );
            mCaidan2DIconList.push_back ( w );
        }
    }

    QListIterator<QQtClickWidget*> itt ( mCaidan2DIconList );
    while ( itt.hasNext() )
    {
        QQtClickWidget* l = itt.next();
        l->setHidden ( true );
    }

    //根据查询命令，或者上报的search命令，把dict里的灯绘制到这里。
    const qint8 colNum = 10;
    QListIterator<QQtClickWidget*> itor ( mCaidan2DIconList );
    int index = 0;
    while ( itor.hasNext() )
    {
        QQtClickWidget* l = itor.next();
        //pline() << l;

        QString iconFile = skin ( QString ( "demo/icon/icon_%1.png" ).arg ( "default" )  );
        //pline() << iconFile;

        QQtClickWidget* w = l;
        w->setPixmap ( iconFile );

        //每行的数目是确定的。
        int i = ( index ) % colNum;

        int iconW = 50;
        int iconH = 50;
        w->setGeometry ( i * iconW, ( index ) / colNum * iconH, iconW - 4, iconH - 4 );
        w->show();

        ui->iconTable->setFixedHeight ( ( ( index ) / colNum + 1 ) * iconH );

        index++;
    }

    ui->caidan2d->setTitle ( "ICON" );
    ui->caidan2d->setBackButton ( "SCENES", "" );
    //sub form

    //main form
    connect ( ui->caidan2d, SIGNAL ( sigBackClick() ),
              this, SLOT ( changeMainForm() ) );

}

void MainForm::initCaidan02E()
{
    //ui->caidan2d->setTitle ( "ICON" );
    ui->caidan2e->setBackButton ( "SCENES", "" );
    //sub form
    ui->label_105->setText ( QString ( "000" ) );
    ui->label_105->installEventFilter ( this );

    //main form
    connect ( ui->caidan2e, SIGNAL ( sigBackClick() ),
              this, SLOT ( changeMainForm() ) );
}

void MainForm::initCaidan021()
{
    //ui->caidan2d->setTitle ( "ICON" );
    ui->caidan21->setBackButton ( "SCENES", "" );
    //sub form

    //main form
    connect ( ui->caidan21, SIGNAL ( sigBackClick() ),
              this, SLOT ( changeMainForm() ) );
}

void MainForm::initCaidan01Huan()
{
    int size = gUsingLightsDict.getList().size();

    for ( int i = 0; i < size; i++ )
    {
        QQtDictionary& node = gUsingLightsDict.getList() [i];

        if ( !node["type"].getValue().isValid() )
            continue;

        QQtClickWidget* posWidget = 0;

        QRect r0 = calculatePosition ( ui->caidan1, i,
                                       ui->caidan1->width() / 2 - 100 - 10,
                                       50,//40,
                                       10 );
        pline() << "caidan 1 [group] button size:" << r0;
        if ( node["type"] == "light" )
        {
            Caidan1Button* btn = new Caidan1Button ( ui->caidan1 );
            btn->lightNo() = node["lightNo."].getValue().toInt();
            btn->sceneName() = node["scene"].getValue().toString();
            QString icon = findIconNameBySceneName ( btn->sceneName() );
            btn->sceneIcon() = "./skin/demo/" + icon;
            //pline() << btn->lightNo() << btn->sceneName() << btn->sceneIcon();
            btn->updateWidget();
            connect ( btn, SIGNAL ( click() ),
                      this, SLOT ( goto01AForm() ) );
            posWidget = btn;
            posWidget->setGeometry ( r0 );

            pline() << btn->size() << btn->iconSize() << btn->iconSize2();
        }
        else if ( node["type"] == "group" )
        {
            Caidan1GroupButton* btnGroup = new Caidan1GroupButton ( ui->caidan1 );
            posWidget = btnGroup;
            btnGroup->setGeometry ( r0 );
            btnGroup->update();
            connect ( btnGroup, SIGNAL ( click() ),
                      this, SLOT ( displayDa() ) );

            //咫尺之间
            QFont font = qApp->font();
            font.setPixelSize ( 24 );
            btnGroup->setTextFont ( font );
            //这个必须设置,原因不明
            btnGroup->setIconSize ( QSize ( 100, 80 ) );


            int size = node.getList().size();
            QQtDictionary& tmp = node;
            for ( int i = 0; i < size; i++ )
            {
                QQtDictionary& node = tmp.getList() [i];

                if ( !node["type"].getValue().isValid() )
                    continue;

                if ( i > 7 )
                    continue;


                Caidan1Button* btn = new Caidan1Button ( btnGroup->widget() );
                btn->lightNo() = node["lightNo."].getValue().toInt();
                btn->sceneName() = node["scene"].getValue().toString();
                QString icon = findIconNameBySceneName ( btn->sceneName() );
                btn->sceneIcon() = skin ( QString ( "demo/%1" ).arg ( "icon_default.png" ) );
                //pline() << btn->lightNo() << btn->sceneName() << btn->sceneIcon();
                btn->updateWidget();
#if 1
                pline() << btnGroup->widget()->size();
                QRect rrr0 = calculatePosition ( btnGroup->widget(), i,
                                                 30 - 10 - 5,//big - little
                                                 10, //little
                                                 4,//num
                                                 0 );
                pline() << rrr0;
                QFont font = qApp->font();
                font.setPixelSize ( 3 );
                //设置了textFont以后就可以图片正常
                btn->setTextFont ( font );
                btn->setTextFont2 ( font );
                //btn->setIconSize ( QSize ( 40, 40 ) );

                //rrr0.adjust ( 0, 0 + 15, 0, 0 + 15 );
                btn->setGeometry ( rrr0 );
#endif
                /**
                 * QObject会帮助用户释放QWidget子孙的空间
                 * 如果Widget子孙保存在QList里，QList也会释放一次。new空间，delete空间。不是指针哦。
                 * 所以，引发二次free，导致崩溃。
                 * 解决方法：QList，内部保存指针。
                 */
                btnGroup->AddCaidanButton ( btn );

            }

            btnGroup->setText ( node["name"].getValue().toString() );
            pline() << btnGroup->text() << node["lightNo."].getValue().toString();
            //btnGroup->updateCaidanButton();
        }

    }
}

void MainForm::initCaidan01Da ( Caidan1GroupButton* btnGroup )
{
    static QQtClickDialog* daWidget = 0;
    static Caidan1Button* localbtn[12] = {0};

    if ( !daWidget )
    {
        daWidget = new QQtClickDialog ( ui->caidan1 );
        daWidget->setWindowFlag ( Qt::FramelessWindowHint, true );
        daWidget->setObjectName ( "Caidan1daWidget" );
        daWidget->setImageStyle ( QQtClickDialog::QQTZOOM );
        daWidget->setPixmap ( skin ( QString ( "demo/%1" ).arg ( "icon_background.png" ) ) );
        daWidget->setContentsMargins ( 0, 0, 0, 0 );
        daWidget->setGeometry ( 145, 145, 480, 480 );
        connect ( daWidget, SIGNAL ( click() ),
                  daWidget, SLOT ( hide() ) );
        connect ( daWidget, SIGNAL ( click() ),
                  centralForm, SLOT ( show() ) );

        for ( int i = 0; i < 12; i++ )
        {
            localbtn[i] = new Caidan1Button ( daWidget );
            localbtn[i]->hide();
        }
    }

    for ( int i = 0; i < 12; i++ )
    {
        localbtn[i]->hide();
    }

    QList<Caidan1Button*>& btns = btnGroup->allCaidanButton();
    QListIterator<Caidan1Button*> itor ( btns );
    int index = 0;
    while ( itor.hasNext() )
    {
        //if ( index > 3 ) break;

        Caidan1Button* srcBtn = itor.next();
        Caidan1Button* btn = localbtn[index];
        btn->lightNo() = srcBtn->lightNo();
        btn->sceneName() = srcBtn->sceneName();
        QString icon = srcBtn->sceneIcon();
        btn->sceneIcon() = skin ( QString ( "demo/%1" ).arg ( "icon_default.png" ) );
        //pline() << btn->lightNo() << btn->sceneName() << btn->sceneIcon();
        btn->updateWidget();

#if 1
        pline() << btnGroup->widget()->size();
        QRect rrr0 = calculatePosition ( daWidget, index,
                                         240 - 50 - 5,//big - little
                                         50, //little
                                         8,//num
                                         0 );
        pline() << rrr0;
        QFont font = qApp->font();
        font.setPixelSize ( 22 );
        //设置了textFont以后就可以图片正常
        btn->setTextFont ( font );
        btn->setTextFont2 ( font );
        //btn->setIconSize ( QSize ( 40, 40 ) );
        btn->setIconSize ( QSize ( 100, 80 ) );

        //rrr0.adjust ( 0, 0 + 15, 0, 0 + 15 );
        btn->setGeometry ( rrr0 );
        btn->show();
#endif
        index++;
    }
    centralForm->hide();

    static QQtLabel* label = new QQtLabel ( daWidget );
    label->setText ( btnGroup->text() );
    moveCenter ( label, daWidget );

    daWidget->show();
}

void MainForm::initCaidan01A()
{
    ui->caidan1a->setBackButton ( "SELECT", "" );

    //返回01
    connect ( ui->caidan1a, SIGNAL ( sigBackClick() ),
              this, SLOT ( changeMainForm() ) );

    initCaidan01AScene();
}

void MainForm::initCaidan01AScene()
{
    static bool bInited = false;

    //only once
    if ( bInited == true )
        return;
    bInited = true;

    //把scrollArea拉长到相应的大小。宽度保持不变。
    //ui->lightsTableContent->setFixedWidth ( 600 );
    //ui->saw_03a->setMouseTracking ( true );
    //ui->scrollArea_3->setMouseTracking ( true );
    ui->scrollArea->setVerticalScrollBarPolicy ( Qt::ScrollBarAlwaysOff );

    if ( mCaidan1BtnList.size() <  gLightSceneDict.size() )
    {
        int size = gLightSceneDict.size() - mCaidan1BtnList.size();
        for ( int i = 0; i < size; i++ )
        {
            HuanButton* w = new HuanButton ( ui->caidan1acaw );
            //w->setAutoFillBackground(true);
            //w->setAlignment ( Qt::AlignCenter );
            //w->setStyleSheet ( "QLabel{background-color:#0044E7;}" );
            //w->setColor ( QRgb ( 0xFEFEFE ) );
            mCaidan1BtnList.push_back ( w );
        }
    }

    QListIterator<HuanButton*> itt ( mCaidan1BtnList );
    while ( itt.hasNext() )
    {
        HuanButton* l = itt.next();
        l->setHidden ( true );
    }

    //根据查询命令，或者上报的search命令，把dict里的灯绘制到这里。
    const qint8 colNum = 5;
    pline() << gLightSceneDict.getTypeName() << gLightSceneDict.size();
    QQtDictionaryListIterator itor ( gLightSceneDict.getList() );
    int index = 0;
    //过滤第一个 0
    if ( itor.hasNext() )
    {
        itor.next();
        index++;
    }

    while ( itor.hasNext() )
    {
        const QQtDictionary& node = itor.next();
        if ( node.isEmpty() )
        {
            index++;
            continue;
        }

        //pline() << node;

        QString name = node["name"].getValue().toString();
        QString icon = node["icon"].getValue().toString();
        QString iconFile = skin ( QString ( "demo/%1" ).arg ( icon )  );
        //pline() << name << icon << iconFile;

        HuanButton* w = mCaidan1BtnList[index];
        w->setText ( name );
        w->setIcon ( iconFile );
        QFont font = qApp->font();
        font.setPixelSize ( 10 );
        w->setTextFont ( font );
        w->setIconSize ( QSize ( 56, 56 ) );
        //pline() << w;

        connect ( w, SIGNAL ( click() ), this, SLOT ( set01ASceneEdit() ) );
        //connect ( w, SIGNAL ( doubleClick() ), this, SLOT ( goto021Form() ) );

        //每行的数目是确定的。
        int i = ( index - 1 ) % colNum;

        int iconW = 60;
        int iconH = 80;
        w->setGeometry ( i * iconW, ( index - 1 ) / colNum * iconH, iconW - 4, iconH - 4 );
        w->show();

        ui->caidan1acaw->setFixedHeight ( ( ( index - 1 ) / colNum + 1 ) * iconH );

        index++;
    }
}

void MainForm::changeCurrentForm()
{
    QObject* o = sender();

    if ( ui->w301 == o )
        //page control a
        ui->stackedWidget->setCurrentIndex (
            ui->stackedWidget->indexOf ( ui->caidan3a ) );
    else if ( ui->w302 == o )
        //page control b
        ui->stackedWidget->setCurrentIndex (
            ui->stackedWidget->indexOf ( ui->caidan3b ) );
    else if ( ui->w303 == o )
        //page control c
        ui->stackedWidget->setCurrentIndex (
            ui->stackedWidget->indexOf ( ui->caidan3c ) );
    else if ( ui->w304 == o )
        //page control d
        ui->stackedWidget->setCurrentIndex (
            ui->stackedWidget->indexOf ( ui->caidan3d ) );
    else if ( ui->w401 == o )
        //page setup a
        ui->stackedWidget->setCurrentIndex (
            ui->stackedWidget->indexOf ( ui->caidan4a ) );
    else if ( ui->w402 == o )
        //page setup b
        ui->stackedWidget->setCurrentIndex (
            ui->stackedWidget->indexOf ( ui->caidan4b ) );
    else if ( ui->w403 == o )
        //page setup c
        ui->stackedWidget->setCurrentIndex (
            ui->stackedWidget->indexOf ( ui->caidan4c ) );
    else if ( ui->w405 == o )
        //page setup e
        ui->stackedWidget->setCurrentIndex (
            ui->stackedWidget->indexOf ( ui->caidan4e ) );

    centralForm->hide();
}

void MainForm::changeMainForm()
{
    QObject* o = sender();

    if ( ui->caidan4b == o
         || ui->caidan4a == o
         || ui->caidan4c == o
         || ui->caidan4e == o
       )
        //page setup main
        ui->stackedWidget->setCurrentIndex (
            ui->stackedWidget->indexOf ( ui->caidan4 ) );
    else if ( ui->caidan3a == o
              || ui->caidan3b == o
              || ui->caidan3c == o
              || ui->caidan3d == o
            )
    {
        //page control main
        ui->stackedWidget->setCurrentIndex (
            ui->stackedWidget->indexOf ( ui->caidan3 ) );
    }
    //菜单2回到select页
    else if ( ui->caidan2 == o
              //菜单1a返回1
              || ui->caidan1a == o
            )
    {
        //page control main
        ui->stackedWidget->setCurrentIndex (
            ui->stackedWidget->indexOf ( ui->caidan1 ) );
    }
    else if ( ui->caidan2b == o
            )
    {
        //page control main
        ui->stackedWidget->setCurrentIndex (
            ui->stackedWidget->indexOf ( ui->caidan2 ) );
        //这里不显示centrelForm,所以返回.
        return;
    }
    else if ( ui->caidan2c == o
              || ui->caidan2d == o
              || ui->caidan2e == o
              || ui->caidan21 == o
            )
    {
        //page control main
        ui->stackedWidget->setCurrentIndex (
            ui->stackedWidget->indexOf ( ui->caidan2b ) );
        //这里不显示centrelForm,所以返回.
        return;
    }
    centralForm->show();
}

void MainForm::on_lightSpeedSlider_valueChanged ( int value )
{
    QSettings set;
    set.setValue ( "lightSpeed", value );
    set.sync();
}

void MainForm::slotPlayOut()
{
    //读取wav文件，在频谱页面播放出来。
    QByteArray s0 = wavManager.readAll();
    audioManager.write ( s0 );

    //获取一次采样的数据数。
    int bytes = wavManager.inputAudioFormat().channelCount()
                * wavManager.inputAudioFormat().sampleSize() / 8;

    QList<QPointF>& nodes = ui->wMusic->getKNotes();
    //nodes.clear();
    while ( !nodes.isEmpty() )
        nodes.removeFirst();

    int index  = -100;
    for ( int i = 0; i < s0.size(); i += bytes )
    {
        char c = s0[i];
        QPointF p0;
        p0.setX ( index++ );
        p0.setY ( qint8 ( c ) / 5 );
        nodes << p0;
    }
    ui->wMusic->generateCurves();
}

void MainForm::slotLabelClicked()
{
    QObject* obj = sender();
    QQtColorLabel* label = ( QQtColorLabel* ) obj;
    QRgb color = label->getColor();
    if ( color == 0xFEFEFE )
        label->setColor ( QRgb ( 0xEEFF49 ) );

    //白色切换为选中色
    //选中色切换为白色
}

void MainForm::on_pushButton_2_clicked()
{
    wavManager.stopInput();
    audioManager.stopOutput();

    audioManager.startDefaultOutput();
    wavManager.startInput();
}

void MainForm::on_pushButton_search_clicked()
{
    ui->lightsTableContent;
    init4ASearchingLights();
}

void MainForm::goto02BForm()
{
    ui->stackedWidget->setCurrentIndex ( ui->stackedWidget->indexOf ( ui->caidan2b ) );
}

void MainForm::preGoto02CForm ( LingWidget* widget )
{
    mCurLing = widget;
    goto02CForm();
}

void MainForm::goto02CForm()
{
    pline() << "goto 2c";
    ui->stackedWidget->setCurrentIndex ( ui->stackedWidget->indexOf ( ui->caidan2c ) );
}

void MainForm::goto02DForm()
{
    ui->stackedWidget->setCurrentIndex ( ui->stackedWidget->indexOf ( ui->caidan2d ) );
}

void MainForm::goto02EForm()
{
    pline() << "goto 2e";
    ui->stackedWidget->setCurrentIndex ( ui->stackedWidget->indexOf ( ui->caidan2e ) );
}

void MainForm::goto021Form()
{
    ui->stackedWidget->setCurrentIndex ( ui->stackedWidget->indexOf ( ui->caidan21 ) );
}

void MainForm::displayDa()
{
    QObject* obj = sender();
    Caidan1GroupButton* btnGroup = ( Caidan1GroupButton* ) obj;
    initCaidan01Da ( btnGroup );
}

void MainForm::goto01AForm()
{
    //在这里初始化01B的一些变量
    centralForm->hide();
    QObject* obj = sender();
    Caidan1Button* btn = ( Caidan1Button* ) obj;
    ui->lineEdit->setText ( QString::number ( btn->lightNo() ) );
    ui->lineEdit_5->setText ( btn->sceneName() );
    ui->stackedWidget->setCurrentIndex ( ui->stackedWidget->indexOf ( ui->caidan1a ) );
}

void MainForm::set01ASceneEdit()
{
    QObject* obj = sender();
    HuanButton* btn = ( HuanButton* ) obj;
    ui->lineEdit_5->setText ( btn->text() );
}

void MainForm::lingColorChanged ( QRgb rgb )
{
    ui->widget_20->setColor ( rgb );
    //ui->widget_20->setAutoFillBackground ( true );
    //QPalette plt = ui->widget_20->palette();
    //plt.setColor ( QPalette::Background, QColor ( rgb ) );
    //ui->widget_20->setPalette ( plt );
    //ui->widget_20->update();

    ui->label_123->setText ( QString ( "%1" ).arg ( qRed ( rgb ), 3, 10, QChar ( '0' ) ) );
    ui->label_125->setText ( QString ( "%1" ).arg ( qGreen ( rgb ), 3, 10, QChar ( '0' ) ) );
    ui->label_127->setText ( QString ( "%1" ).arg ( qBlue ( rgb ), 3, 10, QChar ( '0' ) ) );

    ui->caidan2c->update();

    mCurLing->setColor ( QColor ( rgb ) );
    ui->sceneSlider->update();
}

void MainForm::setCurrentIndex ( int index )
{
    ui->stackedWidget;
    ui->stackedWidget->setCurrentIndex ( index );
    if ( index == 1 )
    {
        centralForm->hide();
    }
    else
    {
        centralForm->show();
    }
}


bool MainForm::eventFilter ( QObject* watched, QEvent* event )
{
    if ( event->type() == QEvent::Paint )
        return HuanFrame::eventFilter ( watched, event );

    if ( watched == ui->label_105
         || watched == ui->label_5
         || watched == ui->label_6
         || watched == ui->label_7
         || watched == ui->label_8
         || watched == ui->label_9
       )
    {
        QLabel* label  = ( QLabel* ) watched;
        static int pre_pos = 0;
        if ( event->type() == QEvent::MouseButtonPress )
        {
            QMouseEvent* e = ( QMouseEvent* ) event;
            pre_pos = e->pos().y();
            e->accept();
            return true;
        }
        else if ( event->type() == QEvent::MouseMove )
        {
            QMouseEvent* e = ( QMouseEvent* ) event;
            int number = label->text().toInt();
            int pos = e->pos().y();
            if ( pos > pre_pos )
            {
                if ( number > 0 )
                    number--;
                label->setText ( QString ( "%1" ).arg ( number, 2, 10, QChar ( '0' ) ) );
            }
            else
            {
                if ( number < 999 )
                    number++;
                label->setText ( QString ( "%1" ).arg ( number, 2, 10, QChar ( '0' ) ) );
            }
            pre_pos = pos;
            e->accept();
            return true;
        }
        else if ( event->type() == QEvent::MouseButtonRelease )
        {
            QMouseEvent* e = ( QMouseEvent* ) event;
            pre_pos = e->pos().y();
            e->accept();
            return true;
        }
    }

    return HuanFrame::eventFilter ( watched, event );
}
